package com.leyou.order.interceptors;

import com.leyou.common.auth.JwtUtils;
import com.leyou.common.auth.Payload;
import com.leyou.common.auth.UserInfo;
import com.leyou.common.constants.UserTokenConstants;
import com.leyou.common.utils.CookieUtils;
import com.leyou.order.utils.UserHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

/**
 * @author 虎哥
 */
public class UserInterceptor implements HandlerInterceptor {
    /**
     * 前置拦截，会在controller中的每个handler执行前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取token
        String token = CookieUtils.getCookieValue(request, UserTokenConstants.COOKIE_NAME);
        // 解析token
        Payload<UserInfo> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, UserInfo.class);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("解析用户信息失败！", e);
        }
        // 获取当前登录的用户
        UserInfo user = payload.getUserInfo();
        // 保存用户
        UserHolder.setUser(user);
        return true;
    }

    /**
     * 后置拦截，是在handler执行完成以后，视图渲染之前执行
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    /**
     * 最终方法，如果前面代码抛出异常或者前面方法正常完成，视图渲染结束，都会进入这个方法
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserHolder.removeUser();
    }
}
